<?php

namespace app\index\controller;

use think\Controller;
use think\Facade\Request;
use think\Db;
use PHPExcel_IOFactory;
use PHPExcel;
use Units\Area;
use Units\RoutePlanner;
use Units\Http;
use think\Facade\Config;
use app\index\model\Router as Model;
use app\index\model\Vehicle;
use app\index\model\Order as OrderModel;
use app\index\model\Customer;
class Router extends Base
{


    /**
     * 显示地图
     *
     * @return \think\Response
     */
    public function showRouter()
    {
        $wareHouse = Request::get('wareHouse');
        return $this->fetch('router/router');
    }

    /**
     * .
     * 获取路线
     * @return \think\Response
     */
    public function router()
    {
        $warehouse = Request::post('warehouse');
        $routers = Model::where(['day'=>date('Y-m-d'),'warehouse'=>$warehouse])->select()->toArray();
        foreach ( $routers as $key=>$item ) {
            $routers[$key] = array_map(function($value){
                    return  is_json($value) ? json_decode( $value, true ) : $value;
            },$item);
        }
        echo json_encode(['code'=>'200','body'=>$routers],JSON_UNESCAPED_UNICODE);
    }



    public function updateRouter()
    {
          $post = input('post.');
          $post['day'] = date('Y-m-d');
          $res = Model::create($post);
          if($res){
              echo json_encode(['code'=>'200','body'=>'UPDATE SUCCESS']);
          }else{
              echo json_encode(['code'=>'201','body'=>'UPDATE FAIL']);
          }

    }

    /**
     * 从excle读取输入，规划好路线写入，数据库
     */
    public function import()
    {
           die;
            $wareHouse = Request::post('warehouse');
            $objPHPExcel = \PHPExcel_IOFactory::load($this->getUploadExcle());
            $objPHPExcel->setActiveSheetIndex(0);
            $routers=[];
            $i=1;
            $start = time();
            while (true){
                $i++;
                $router['CustID'] = $objPHPExcel->getActiveSheet()->getCell("D{$i}")->getValue();
                $router['CustName'] = $objPHPExcel->getActiveSheet()->getCell("E{$i}")->getValue();
                $router['Contact'] = $objPHPExcel->getActiveSheet()->getCell("F{$i}")->getValue();
                $router['Address'] = $objPHPExcel->getActiveSheet()->getCell("G{$i}")->getValue();
                $router['City'] = $objPHPExcel->getActiveSheet()->getCell("H{$i}")->getValue();
                $router['CustomerNotes'] = $objPHPExcel->getActiveSheet()->getCell("AD{$i}")->getValue();
                $router['Region'] = $objPHPExcel->getActiveSheet()->getCell("I{$i}")->getValue();
                $router['LoadAmount'] = $objPHPExcel->getActiveSheet()->getCell("AA{$i}")->getValue();
                $router['UnloadAmount'] = $objPHPExcel->getActiveSheet()->getCell("AB{$i}")->getValue();
                $router['TimeOnSite'] = $objPHPExcel->getActiveSheet()->getCell("AH{$i}")->getValue();
                if(!$router['CustID']) break;
                $routers[] = $router;

            }
        file_put_contents('order.json', json_encode( $routers ));
        echo "done";
            die;
        $center = ['lat'=>Request::post('lat'),'lng'=>Request::post('lng')];
        $area = new Area();
        //通过地址查找经纬度
        $routers = $this->getLatAndLng($routers);
        $data = $area->regionalPoint($center , $routers);
        $RoutePlanner = new RoutePlanner();
        $data = $RoutePlanner->plan($center,$data);
        foreach ( $data as $key=> $val ) {
            $arr=[];
            $arr['start'] = $center;
            $users = $this->getCustomerInfo($val);
            if(count( $val ) > 1 ){
                $arr['end'] = array_pop($val);
                $arr['waypoints'] = $val;
            }else{
                $arr['end'] = $val[0];
                $arr['waypoints'] = '';
            }


            Db::name('routers')->insert([
                'day'=>date('Y-m-d'),
                'id'=>$this->guid(),
                'users'=>json_encode($users,JSON_UNESCAPED_UNICODE),
                'routers'=>json_encode($arr,JSON_UNESCAPED_UNICODE),
                'warehouse'=>$wareHouse
            ]);

        }
        echo "SUCCESS <a href='".url('/tms/router')."'>查看地图</a>";
    }

    /**获取上传文件
     * @return string
     */
    public function getUploadExcle(){
        $file = request()->file('router');
        $info = $file->move( '../uploads');
        if($info){
            return $uploadFile = "../uploads/".$info->getSaveName();
        }else{
            exit($file->getError());
        }
    }

    /**
     * 遍历每个客户信息和备注信息
     * @param $data
     * @return array
     */
    public function getCustomerInfo($data){
        foreach ( $data as $key=>$val ) {
            $ret[]= [
                'CustName' => $val['CustName'],
                'Contact'=> $val['Contact'],
                'Address'=> $val['Address'].','.$val['CustName'],
                'CustomerNotes'=> $val['CustomerNotes']
            ];
        }
        return $ret;
    }

    /**
     * 通过地址获取经纬度
     * @param string $url  地址
     * @return array 经纬度
     */
    private function getLatAndLng($url = "1051 Pacific Marina,Alameda,CA"){
        $url = "https://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($url)."&key=".Config::get('GOOGLE_MAP_API_KEY');
        $client = new \GuzzleHttp\Client();
       // $client->setDefaultOption();
        $res = $client->request('GET', $url, [
            'verify'=>false,
            'proxy' => [
                'https' => 'tcp://localhost:80', // Use this proxy with "https",
            ]
        ]);




    }
    /**
     * 通过地址获取经纬度
     * @param string $url  地址
     * @return array 经纬度
     */
    private function getLatAndLng1($url = "1051 Pacific Marina,Alameda,CA"){
        $url = "https://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($url)."&key=".Config::get('GOOGLE_MAP_API_KEY');
        $res = Http::instance()->request( $url , 'post')->data();
        $res = json_decode($res , true);
        if( $res['status']=='OK') {
            return $res['results']['0']['geometry']['location'];
        }else{
            return ['lat'=>'-1','lng'=>'-1'];
        }



    }

    public function showImport(){
        return $this->fetch('router/import');
    }







    public function GetRouters(){
            $id = Request::post('id');
            $data = Model::where(['id'=>$id])->find()->toArray();
            echo json_encode(['code'=>200,'body'=>json_decode($data['routers'] , true) ]);
    }

    /**
     * 更新分配司机数据
     */
    public function UpdateRouterDriver()
    {
         $data = Request::post('data');
         $data =  json_decode( $data , true );
         foreach ( $data as $item )
         {
             Model::where(['id'=>$item['router_id']])->update(['driver_id'=>$item['driver_id']]);
         }
         returnAjax('200','SUCCESS');
    }

    public function delete()
    {
        $id = Request::post('id');
        Model::where(['id'=>$id])->delete();
        returnAjax('200','SUCCESS');
    }

    /**
     * 获取某一天Router数据(有司机数据和车辆数据)
     */
    public function getRouterByDate()
    {
         $day = Request::post('day');
         $warehouse = Request::post('warehouse');
         if(!$day)
         {
             returnAjax('201','Invalid Parameter day');
         }
        if(!$warehouse)
        {
            returnAjax('201','Invalid Parameter warehouse');
        }
        $data = Model::where(['day'=>$day,'warehouse'=>$warehouse])->select()->toArray();
         if(! $data)
         {
             returnAjax('201','No Data');
         }
        $data = array_map( function( $value ){
               $data = $value;
               $data['router_edge_points'] = json_decode( $value['router_edge_points'] , true );
               $data['schedule'] = json_decode( $value['schedule'] , true );
               $data['routers'] = json_decode( $value['routers'] , true );
               return $data;


        }, $data);
        returnAjax('200',$data);
    }

    /**
     * 获取某一天Territoy数据(没有司机数据和车辆数据)
     */
    public function getTerritoyByDate()
    {
        $warehouse  = Request::post('warehouse');
        $day = Request::post('day');
        $data = Model::where(['warehouse'=>$warehouse,'day'=>$day])->select()->toArray();
        if(!$data)
        {
            returnAjax('201',$data);
        }
        foreach ( $data as $key=>$value)
        {
            $data[$key]['router_edge_points'] = json_decode( $value['router_edge_points'] , true );
        }
        returnAjax('200',$data);
    }



}
